<?php
class MyController extends BaseApiController
{

    function init()
    {
        parent::init();
    }


    #推送初始化，记录device_token
    function setPushTokenAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $push_token = !empty($_REQUEST['push_token']) ? urldecode(trim($_REQUEST['push_token'])) : "";

        if(empty($push_token)){
            $return_code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        $user_model = new UserModel();
        $data = array(
            'push_token' => $push_token
        );
        $ret = $user_model->updateData($data, $uid); //查询该设备是否存在
        if(!$ret){
            $return_code = 10001; //缺少参数
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $data);
    }


    #是否有未读消息
    function myNoticeAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $data = array();
        $notice_model = new NoticeModel();

        $condition = array(
            'uid' => $uid,
            'isnew' => 1,
            'type' => '1' //系统消息
        );
        $data['sys_count'] = $notice_model->getListByAdminCount($condition);


        $condition = array(
            'uid' => $uid,
            'isnew' => 1,
            'type' => '2,3' //系统消息
        );
        $data['fri_count'] = $notice_model->getListByAdminCount($condition);
        $data['count'] = $data['sys_count']  +  $data['fri_count'];
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $data);
    }

    #友盟推送
    function pushAction(){
        #友盟
        $note = '测试';
        $title = '测试';
        $push_msg = array(
            'type' => '2',// 1 公共消息    2 ios   3 Android   4 指定用户
            'title' => $title,
            'alert' => array('title' => $title, 'body' => $note, 'subtitle' => ''),
            'text' => $note,
            'description' => mb_substr( $title, 0, 15, 'utf-8').'...',
            'production_mode' => false //正式/测试环境
        );
        $extra = array(  //扩展字段
            'type' => 1,
        );

        $push_msg_model = new PushMsg();  //友盟
        $array = array(
            '4598f9669347fde52bb84a73641df167eb16c0245de7c119fe6adbfa4801e6a6',
        );
        foreach($array as  $key => $val){
            $ret = $push_msg_model->pushMsg(2, $push_msg, $array, $extra);
            print_r($ret);
        }

        die;
    }


    #修改个人信息
    function editUserInfoAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $nickname = isset($_REQUEST['nickname']) ? trim($_REQUEST['nickname']) : ''; //nicheng
        $avatar = isset($_REQUEST['avatar']) ? trim($_REQUEST['avatar']) : ''; //头像

        $ext_name = isset($_REQUEST['ext_name']) ? trim($_REQUEST['ext_name']) : "";
        $base64_string = isset($_REQUEST['base64_string']) ? trim($_REQUEST['base64_string']) : "";

        $data = $return = array();
        $user_model = new UserModel();
        if(!empty($base64_string)){
            $avatar = $user_model->updateAvatar($uid,$upload_filed = 'upload_file',$ext_name,$base64_string);

            $user_list_model = new UserListModel();
            $friend_data = array('avatar' => $avatar);
            $data['avatar'] = $avatar;
            $return['avatar'] = QINIU_DOMAIN . $avatar;
            $user_list_model->updateDataByFriendid($friend_data, $uid);
        }
        if(!empty($nickname)){
            $data['nickname'] =  $return['avatar'] = $nickname;
        }

        $user_model->updateData($data, $uid);
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE,  $return);
    }


    #每日分享
    function picShareAction(){
        $share_img = array(
            '1141964905f1a935bdf3f79.88749535.png', '21243685735f1a9ce0708fa3.26634021.png',
            '4367375985f1a9d03e641e2.16390087.png', '9298270955f1a9d235f37e1.57211677.png',
            '4857746775f1a9e2db5f118.48345875.png', '19079702845f1a9e7e6c7c48.32669675.png',
            '2206825125f1a9e9dc56412.82990709.png', '1974407385f1a9ebc4b9aa4.88128646.png',
            '9468239195f1a9ed97d1298.62182805.png',


            );
        $return = array(
            'pic' => 'http://qnssl.touhaoshiwan.com/1141964905f1a935bdf3f79.88749535.png'
        );
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $return);
    }



    #vip 页面显示
    function vipAction(){

        $data = array(
            'vip' => array(
                array(
                    'id' => 'com.xiaonianlang.where.ContinuousMonthly', //苹果那边设定的ID
                    'sale' => "6折",
                    'title' => "连续包月VIP",
                    'price' => "128",
                    'rate' => "78",
                    'note' => "仅2.51元/天",
                    'desc' => '到期前自动扣费,每月78元,可随时取消~'
                ),
                array(
                    'id' => 'com.xiaonianlang.where.monthlyVIP',
                    'sale' => "",
                    'title' => "月度VIP",
                    'price' => "",
                    'rate' => "128",
                    'note' => "仅4.12元/天",
                    'desc' => '1个月vip会员'
                ),
                array(
                    'id' => 'com.xiaonianlang.where.halfYearVIP',
                    'sale' => "",
                    'title' => "半年VIP",
                    'price' => "",
                    'rate' => "188",
                    'note' => "仅1.03元/天",
                    'desc' => '6个月vip会员'
                )
            ),
            'banner' => array(
                'title' => '支付',
                'img' => '',
            )
        );

        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $userer_model = new UserModel();
        $user_info = $userer_model->getUserInfoByUid($uid);
        if(empty($user_info['member'])){  //不是会员的话，就显示优惠价格
            $data['vip'][] = array(
                'id' => 'com.xiaonianlang.where.YearVIP',
                'sale' => "限时特价",
                'title' => "年度VIP",
                'price' => "",
                'rate' => "198",
                'note' => "仅0.54元/天",
                'desc' => '12个月vip会员'
            );
        }

        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $data);
    }


    #会员充值前
    function makeOrderAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $vip_id = isset($_REQUEST['vip_id']) ? trim($_REQUEST['vip_id']) : ''; //充值选项ID

        $user_model = new UserModel();
        $user_info = $user_model->getUserInfoByUid($uid);
        $start_time = time();
        if($user_info['mem_expire'] > time()){ //查看现有的会员有咩有过期，没有过期的话，在此基础上叠加
            $start_time = $user_info['mem_expire'];
        }

        $order_model = new OrderModel();
        $vip_model = new VipModel();
        $expi = $vip_model->getExprie($start_time, $vip_id);//获取充值的时间
        if(empty($expi)){
            $return_code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        $insert = array(
            'uid' => $uid,
            'vip_id' => $vip_id,
            'status' => 0,
            'mem_expire' => $expi,
            'created_at' => time()
        );
        $ret = $order_model->addData($insert);
        if(empty($ret)){
            $return_code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        $insert['id'] = $ret;
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $insert);
    }

    #充值会员
    function verifyOrderAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $receipt = isset($_REQUEST['receipt']) ? ($_REQUEST['receipt']) : ''; //苹果返回的数据
        $vip_id = isset($_REQUEST['vip_id']) ? trim($_REQUEST['vip_id']) : ''; //充值选项ID
        $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : ''; //充值选项ID
        $password = '4742a793bf3747a0a28a9d211a36fa0b';

        $receipt = urldecode($receipt);
        $receipt = str_replace('%2B', '+', $receipt);

        if(empty($order_id) || empty($vip_id)){
            $return_code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        $order_model = new OrderModel();
        $order_info = $order_model->getDataById($order_id);
        if(!empty($order_info) && $order_info['status'] == 2){
            $user_update = array(
                "member" => 1,
                "mem_expire" => $order_info['mem_expire']
            );
            return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $user_update);
        }

        $vip_model = new VipModel();
//        $string_url = "https://sandbox.itunes.apple.com/verifyReceipt"; //测试服
        $string_url = "https://buy.itunes.apple.com/verifyReceipt"; //正式服

        $data = '{"receipt-data":"'.$receipt.'","password":"'.$password.'"}';
        $ret = $vip_model->post_curl($string_url, $data);  //苹果核对失败？？
        if(empty($ret)){
            $return_code = 26002; //订单异常
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        if($ret['status'] == 0){
            $apple_id = $ret['receipt']['in_app'][0]['transaction_id'];
//            $product_id = $ret['receipt']['in_app'][0]['product_id'];
            $update = array(
                'updated_at' => time(),
                'apple_id' => $apple_id,
                'status' => '2',
            );
            $ret = $order_model->updateDataById($update, $order_id);
            if(!$ret){
                $return_code = 10011; //缺少参数
                $msg = $this->_error_msg->system_errors[$return_code];
                return $this->echo_message($msg,$return_code);
            }

            $user_model = new UserModel();
            $user_update = array(
                'member' => 1,
                'mem_expire' => $order_info['mem_expire'],
            );
            $user_model->updateData($user_update, $uid);

            #添加付款成功记录
            $notice_model = new NoticeModel();
            $note = array(
                'uid' => $uid,
                'title' => '付款记录',
                'type' => 1,
                'note' => '您已成功购买会员',
                'created_at' => time(),
            );
            $notice_model->addData($note);
            return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $user_update);
        }elseif($ret['status'] == 21007){

            $string_url = "https://sandbox.itunes.apple.com/verifyReceipt"; //测试
            $data = '{"receipt-data":"'.$receipt.'","password":"'.$password.'"}';
            $ret = $vip_model->post_curl($string_url, $data);  //苹果核对失败？？
            if(empty($ret)){
                $return_code = 26002; //订单异常
                $msg = $this->_error_msg->system_errors[$return_code];
                return $this->echo_message($msg,$return_code);
            }

            if($ret['status'] == 0) {
                $apple_id = $ret['receipt']['in_app'][0]['transaction_id'];
                $update = array(
                    'updated_at' => time(),
                    'apple_id' => $apple_id,
                    'status' => '2',
                );
                $ret = $order_model->updateDataById($update, $order_id);
                if (!$ret) {
                    $return_code = 10011; //缺少参数
                    $msg = $this->_error_msg->system_errors[$return_code];
                    return $this->echo_message($msg, $return_code);
                }

                $user_model = new UserModel();
                $user_update = array(
                    'member' => 1,
                    'mem_expire' => $order_info['mem_expire'],
                );
                $user_model->updateData($user_update, $uid);

                #添加付款成功记录
                $notice_model = new NoticeModel();
                $note = array(
                    'uid' => $uid,
                    'title' => '付款记录',
                    'type' => 1,
                    'note' => '您已成功购买会员',
                    'created_at' => time(),
                );
                $notice_model->addData($note);
                return $this->echo_message(self::RETURN_SUCCESS_MSG, self::RETURN_SUCCESS_CODE, $user_update);
            }else{
                $ret['data'] = $data;
                $return_code = 10010; //缺少参数
                $msg = $this->_error_msg->system_errors[$return_code];
                return $this->echo_message($msg,$return_code,$ret);
            }

        }else{
            $ret['data'] = $data;
            $return_code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code,$ret);
        }
    }


    #注销账号
    function cancelAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口

        $user_model = new UserModel();
        $user_info = $user_model->getUserInfoByUid($uid);

        $user_cancel_model = new UserCancelModel();
        $user_cancel_model->beginTransaction();
        $user_cancel_model->addData($user_info);
        $ret = $user_cancel_model->getUserInfoByUid($uid);
        if(!$ret){
            $user_cancel_model->rollback();
            $return_code = 20048; //操作失败
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        $ret = $user_model->deleteDate($uid);
        if(!$ret){
            $user_cancel_model->rollback();
            $return_code = 10024; //数据库失败
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        #删除好友关系
        $user_list_model = new UserListModel();
        $user_list_model->deleteDataByUid($uid);
        $user_list_model->deleteDataByFriendId($uid);

        #删除我的正在进行的约会
        $date_records_model = new DateRecordsModel();
        $appointment_model = new AppointmentModel();
        $date_info = $date_records_model->getDateByUid($uid);//我创建的正在进行的约会
        $update = array(
            'status' => 2   //结束
        );
        if($date_info){
            $date_records_model->updateDataById($update, $date_info['id']);
            $appointment_model->updateDataByDateId($update, $date_info['id']);
        }

        #非我自己组建的约会
        $my_date = $appointment_model->getDataByUid($uid);
        if($my_date){
            $appointment_model->updateDataByDateId($update, $my_date['id']);
        }

        $user_cancel_model->commit();
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
    }



    #邀请好友
    function shareAction(){
        $uid = $this->uid; //base接口中需要用户信息,没有用户信息不会访问到接口
        $type = isset($_REQUEST['type']) ? ($_REQUEST['type']) : '1'; //type,1-邀请好友，2-邀请约会
        $date_id = isset($_REQUEST['date_id']) ? ($_REQUEST['date_id']) : ''; //聚会ID
        $return = array();

        if($type == 1){
            $return['title'] = "让守护看得见，让关心有着落";
            $return['note'] = "下载添加好友，随时守护彼此位置安全。";
            $return['link'] = "https://where.th006.cn/share/index?friend_id=".$uid."&from=invite";
        }else{
            $return['title'] = "您的好友邀请您加入聚会";
            $return['note'] = "在哪app让聚会看得到彼此距离。";
            $return['link'] = "https://where.th006.cn/share/index?friend_id=".$uid."&date_id=".$date_id."&from=date";
        }
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE, $return);
    }

}